package com.itwhy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itwhy.domain.dto.PageDTO;
import com.itwhy.domain.po.Address;
import com.itwhy.domain.po.User;
import com.itwhy.domain.query.UserQuery;
import com.itwhy.domain.vo.AddressVO;
import com.itwhy.domain.vo.UserVO;
import com.itwhy.enums.UserStatus;
import com.itwhy.mapper.UserMapper;
import com.itwhy.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <P>ClassName UserServiceImpl</P>
 * @since  2023/11/21 15:50
 * @author 王海云
 * @version 1.0.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    @Transactional
    public void updateBalanceById(Long id, Integer money) {
        // 1. 查询用户
        User user = getById(id);
        // 2. 校验用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常！");
        }
        // 3.校验余额
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
        // 4.扣除金额
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁
                .update();
    }

    @Override
    public List<User> queryUsers(UserQuery userQuery) {
        return lambdaQuery()
                .like(userQuery.getName() != null, User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .ge(userQuery.getMinBalance() != null, User::getBalance, userQuery.getMinBalance())
                .le(userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMaxBalance())
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        // 1.根据ID查询用户
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常！");
        }
        // 2.根据用户ID查询地址列表
        List<Address> addressList = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        // 3.将UserPO转为UserVo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        // 4.将addressList转为UserVO
        if (CollUtil.isNotEmpty(addressList)) {
            userVO.setAddressVOList(BeanUtil.copyToList(addressList, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        // 1.查询用户列表信息
        List<User> userList = listByIds(ids);
        if (CollUtil.isEmpty(userList)) {
            return Collections.emptyList();
        }
        // 2.查询地址列表信息
        List<Address> addressList = Db.lambdaQuery(Address.class).in(Address::getUserId, ids).list();
        // 3.地址转为VO
        List<AddressVO> addressVOList = BeanUtil.copyToList(addressList, AddressVO.class);
        // 4.用户地址集合分组处理，相同用户的放入一个集合(组)中
        Map<Long, List<AddressVO>> collect = new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)) {
            collect = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        List<UserVO> userVOList = new ArrayList<>(userList.size());
        for (User user : userList) {
            // 将PO转为VO
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            // 将地址存入
            userVO.setAddressVOList(collect.get(user.getId()));
            // 存入集合
            userVOList.add(userVO);
        }
        return userVOList;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer maxBalance = userQuery.getMaxBalance();
        Integer minBalance = userQuery.getMinBalance();
        Integer pageNo = userQuery.getPageNo();
        Integer pageSize = userQuery.getPageSize();
        Integer status = userQuery.getStatus();
        PageDTO<UserVO> userVOPageDTO = new PageDTO<>();
        // 1.构建分页条件
        Page<User> page = userQuery.toMpPageDefaultSortByUpdateTimeDesc();
        // 2.分页查询
        Page<User> pageRs = lambdaQuery().like(name != null,User::getUsername, name)
                .lt(maxBalance != null, User::getBalance, maxBalance)
                .gt(minBalance != null, User::getBalance, minBalance)
                .eq(status != null, User::getStatus, status)
                .page(page);
        // 3.封装结果
        return PageDTO.of(pageRs, user -> {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setUsername(userVO.getUsername().substring(0, userVO.getUsername().length() - 2) + "**");
            return userVO;
        });
    }
}
